package com.feihong.txgw.ui.fragment.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.feihong.txgw.R;
import com.feihong.txgw.app.App;
import com.feihong.txgw.message.ForceLogoutMessage;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.user.User;
import com.feihong.txgw.ui.activity.setting.MessageListActivity;
import com.feihong.txgw.ui.activity.setting.SettingActivity;
import com.feihong.txgw.ui.activity.user.LoginActivity;
import com.feihong.txgw.ui.activity.user.MyDeliveryAdrActivity;
import com.feihong.txgw.utils.CacheDataManger;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.ScreenUtil;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.greendao.GreenDaoOperateHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;
import me.yokeyword.fragmentation.SupportFragment;

import static com.feihong.txgw.ui.activity.user.LoginActivity.isFrouceLogoutKey;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 */

public abstract class BaseFragment extends SupportFragment {

    public Unbinder unbinder;
    public String tag;
    public static final String TAG = "通讯顾问";
    public View fragmentView = null;
    /**
     * 特定的界面titlelayout
     */
    private View mSpecificStatusLayout;
    /**
     * 默认的界面titleLayout
     */
    private View mDefaultStatusLayout;
    public Context mFragmentContext;
    private SweetAlertDialog pDialog;

//    public ImmersionBar mImmersionBar;

    public boolean isDrakFont = true;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mFragmentContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        setTheme();
        fragmentView = inflater.inflate(setLayoutID(), container, false);
        return fragmentView;
    }

    public abstract void setTheme();

    public abstract int setLayoutID();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        if (view != null && view.findViewById(R.id.img_btn_setting) != null) {
            view.findViewById(R.id.img_btn_setting).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), SettingActivity.class);
                    startActivity(intent);
                }
            });
        }

        if (view != null && view.findViewById(R.id.img_btn_message) != null) {
            view.findViewById(R.id.img_btn_message).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), MessageListActivity.class);
                    startActivity(intent);
                }
            });
        }
        mDefaultStatusLayout = view.findViewById(R.id.fragment_status_layout);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if(!ScreenUtil.setStatusBarDarkFont(_mActivity,isDrakFont)){
            if(mSpecificStatusLayout != null){
                mSpecificStatusLayout.setBackgroundColor(getResources().getColor(R.color.trans));
            }else if(mDefaultStatusLayout != null){
                mDefaultStatusLayout.setBackgroundColor(getResources().getColor(R.color.trans));
            }
        }
//        if (mImmersionBar == null) {
//            mImmersionBar = ImmersionBar.with(this);
//            mImmersionBar.statusBarDarkFont(true).init();
//        }
//        if (mSpecificStatusLayout != null) {
//            mImmersionBar.statusBarView(mSpecificStatusLayout).init();
//        } else if (mDefaultStatusLayout != null) {
//            mImmersionBar.statusBarView(mDefaultStatusLayout).init();
//        }
    }

    public void setSpecificTitleLayout(View view) {
        mSpecificStatusLayout = view;
    }

    /**
     * 获取用户ID
     * 2017.7.25
     * 张鹏
     *
     * @return
     */
    public String getUserId() {
        User userInfo = UserLoginInfo.getUserInfo();
        if (userInfo != null) {
            return userInfo.getUserID();
        } else {
            return null;
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
//        getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 绑定View
     */
    public abstract void initView();

    /**
     * 绑定数据
     */
    public abstract void bindData();


    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void doUserLogin(LoginMessage loginMessage) {
        onUserLogin(loginMessage);
    }

    /**
     * 用户登录状态改变时通知接口 ， 在页面里面需要通知，则onCreateView事件里面必须注册EventBus
     *
     * @param loginMessage
     */
    public abstract void onUserLogin(LoginMessage loginMessage);


    public View findView(int id) {
        if (fragmentView == null) {
            return null;
        }
        return fragmentView.findViewById(id);
    }

    public boolean isUserLogin() {
        if (UserLoginInfo.isUserLogin()) {
            return true;
        }
        return false;
    }

    public boolean fragmentIsOnDestory() {
        if (getActivity() == null) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (getActivity().isDestroyed()) {
                return true;
            }
        } else {
            if (getActivity().getSupportFragmentManager() == null || getActivity().getSupportFragmentManager().isDestroyed()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
//        if(mImmersionBar != null){
//            mImmersionBar.destroy();
//        }
    }

    @Override
    public void onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroyView();
    }

    public void showLoginDialog() {
        showConfirmDialog("未登录", "您还未登录，请先登录！", "登录", "取消",
                new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        Intent loginIntent = new Intent();
                        loginIntent.setClass(getActivity(), LoginActivity.class);
                        startActivity(loginIntent);
                    }
                });
    }

    public void showConfirmDialog(String title, String message, String confirmText, String cancelText, SweetAlertDialog.OnSweetClickListener confirmClickListener) {
        showConfirmDialog(title, message, confirmText, cancelText, confirmClickListener, null);
    }

    public void showConfirmDialog(String title, String message, String confirmText, String cancelText, SweetAlertDialog.OnSweetClickListener confirmClickListener, SweetAlertDialog.OnSweetClickListener cancelClickListener) {
        SweetAlertDialog dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        dialog.setTitleText(title)
                .setContentText(message)
                .setConfirmText(confirmText).setCancelText(cancelText);
        if (confirmClickListener != null) {
            dialog.setConfirmClickListener(confirmClickListener);
        }

        if (cancelClickListener != null) {
            dialog.setCancelClickListener(cancelClickListener);
        }

        dialog.show();
    }

    /**
     * 通用方法，判断用户是否登录，登录了打开页面，没有登录提示登录
     *
     * @param intent
     */
    public void checkLoginAndStartIntent(Intent intent) {
        if (UserLoginInfo.isUserLogin()) {
            startActivity(intent);
        } else {
            showLoginDialog();
        }
    }

    public void showDialog(String title, String message, DialogInterface.OnDismissListener dismissListener, int type) {
        SweetAlertDialog dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        dialog.setTitleText(title);
        dialog.setContentText(message);
        dialog.setNeutralText("知道了");
        if (dismissListener != null) {
            dialog.setOnDismissListener(dismissListener);
        }
        dialog.show();
    }

    /**
     * 待删除
     *
     * @param forceLogoutMessage
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onForceLogoutMsg(ForceLogoutMessage forceLogoutMessage) {
        UserLoginInfo.userExitLogin();
        // 退出登录时  将默认收货地址的缓存清空
        PreferenceTools.putString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, "");
        PreferenceTools.putString("ll_info_result", "");
        //应该把我的->用户名称 还原
        try {
            CacheDataManger.getTotalCacheSize(getActivity()).startsWith("0");
        } catch (Exception e) {

        }
        LoginMessage loginMessage = new LoginMessage();
        loginMessage.setAction(LoginMessage.ACTION_EXIT);
        GreenDaoOperateHelper.delAll();
        EventBus.getDefault().post(loginMessage);
        UserLoginInfo.updateUserToken("");
        App.getApp().lastUpdateToken = 0;
        showDialog(null, "您的身份信息已失效,请重新登录", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.cancel();
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                intent.putExtra(isFrouceLogoutKey, true);
                startActivity(intent);
            }
        }, SweetAlertDialog.SUCCESS_TYPE);
    }

    /**
     * 提示对话框
     *
     * @param title   标题
     * @param message 内容
     */
    public void showDialog(String title, String message) {
        showDialog(title, message, null);
    }

    public void showDialog(String title, String message, DialogInterface.OnDismissListener dismissListener) {
        showDialog(title, message, dismissListener, SweetAlertDialog.SUCCESS_TYPE);
    }

    public void showProgressDialog(String message) {
        showProgressDialog(message, false);
    }

    /**
     * 等待对话框
     *
     * @param message    提示
     * @param cancelable 是否可以返回键来关闭
     */
    public void showProgressDialog(String message, boolean cancelable) {
        if (pDialog != null) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText(message);
        pDialog.setCancelable(cancelable);
        pDialog.show();
    }

    public void dismissProgressDialog() {
        if (pDialog != null) {
            if (pDialog.isShowing()) {
                pDialog.dismissWithAnimation();
            }
            pDialog = null;
        }
    }

    public void showSystemToast(String message) {
        try {
            ToastUtils.cannelToast();
            ToastUtils.getInstance().showShortToast(message);
        } catch (Exception ex) {

        }
    }
}
